# coding=utf-8
from django.http import HttpResponse
from django.utils import simplejson as json
from google.appengine.api import mail
from xml.dom import minidom
import urllib,urllib2

def home(request):
    #res=urllib2.urlopen('http://search.twitter.com/search.json?q=hamphet')
    #res=urllib2.Request('http://search.twitter.com/search.json')
    url='http://search.twitter.com/search.json'
    values={'q' : 'hamphet'}
    data=urllib.urlencode(values)
    req=urllib2.Request(url,data)
    info=json.load(urllib2.urlopen(req))
    html='''
    <html>
    <head><title>search in twitter</title>
    <body>
    '''   
    html=html+str(len(info['results']))+'''</body></html>'''
    return HttpResponse(html)
def detail(request,q):
    #res=urllib2.urlopen('http://search.twitter.com/search.json?q=hamphet')
    #res=urllib2.Request('http://search.twitter.com/search.json')
    url='http://search.twitter.com/search.atom'
    html="""
    <html>
    <head><title>search result in twitter</title>
    <body><center><h1>search result in twitter
    <table>
    """
    end="""</table></center></body></html>"""
    result="""<h2>keyword:"""+q
    count=0
    values={'q' : urllib2.quote(urllib2.unquote(q).encode('utf-8')) }
    data=urllib.urlencode(values)
    req=urllib2.Request(url,data)
    info=minidom.parse(urllib2.urlopen(req))
    entrylist=info.getElementsByTagName('entry')
    for entry in entrylist:
	    count+=1
	    result+="<tr><td colspan=2><strong>result "+str(count)+"</strong></td></tr>"
	    result+="<tr><td>title:</td><td>"+entry.childNodes[7].childNodes[0].nodeValue+"</td></tr>"
	    result+="<tr><td>time:</td><td>"+entry.childNodes[3].childNodes[0].nodeValue+"</td></tr>"
	    result+="<tr><td>link:</td><td>"+entry.childNodes[5].getAttribute('href')+"</td></tr>"
	    result+="<tr><td>author:</td><td>"+entry.childNodes[23].childNodes[1].childNodes[0].nodeValue+"</td></tr>"
    # uncomment next line ,if you want to notice sb by email.
    #mail.send_mail('sender@xxx.com','receiver@xxx.com','search in twitter',result)
    return HttpResponse(html+result+end)
